<script setup lang="ts">
import { computed, onMounted, reactive, ref, unref, watch } from 'vue';
import { useRouter } from 'vue-router';

import { Modal,notification } from 'ant-design-vue';

import {
  asyncOrderStatus,
  getDouyinOrderList,
  getOrderList,
  getOrderLogisticsApi,
  getOrderStatusList,
  update1688Source,
  delAliOrder,
} from '#/api';
import { useTable } from '#/hooks/useTable';
import { auto1688stor, link1688stor, payOrderStore } from '#/store';
import { checkBindOrderApp } from '#/utils';

import CopyItem from '../shopAs/components/copyItem.vue';
import BottomButton from './orderTableCom/bottomButton.vue';
import OrderInfo from './orderTableCom/orderInfo.vue';
import OrderStatus from './orderTableCom/orderStatus.vue';
import PayOrderBox from './orderTableCom/payOrderBox/index.vue';
import ProfitTime from './orderTableCom/profitTime.vue';
import SourceInfo from './orderTableCom/sourceInfo.vue';

const link1688 = link1688stor();
const auto1688 = auto1688stor();
const payOrder = payOrderStore();

const { nowSelectDyShop, bindShopList } = auto1688.auto1688;
const selectShop = ref<any>(nowSelectDyShop?.shopId);
const searchForm = reactive({
  platformCode: '',
  orderType: '',
  shopId: selectShop.value,
  shopName: '',
  dyOrderStatus: '',
  aliOrderStatus: '',
  goodsTitle: '',
  dyOrderId: '',
});

watch(selectShop, () => {
  searchForm.shopId = selectShop.value;
});

const {
  tableData,
  page,
  loading,
  resetParams,
  getList,
  handleCurrentChange,
  handleSizeChange,
} = useTable({
  apiFn: getOrderList,
  params: searchForm,
  callback(data) {
    // console.log(data);
    data.rows = data.rows.map((item: any) => {
      item = {
        ...item,
        ...item.shopOrderAddress,
      };
      return item;
    });
    return data;
  },
});
link1688.getList = getList;
payOrder.getList = getList;
const statusOptionDouDian = ref([]);
const statusOption1688 = ref([]);

function getOrderStatusListApi() {
  getOrderStatusList().then((res) => {
    statusOptionDouDian.value = res.doudian;
    statusOption1688.value = res.ali1688;
  });
}
function asyncOrderStatusApi() {
  asyncOrderStatus({ shopId: selectShop.value }).then((res: any) => {
    if (res) {
      Modal.success({
        title: '提示',
        content: '数据正在后端同步，请稍后查询列表查看',
      });
      //getList();
    }
  });
}

onMounted(() => {
  if (checkBindOrderApp(selectShop.value)) {
    getOrderStatusListApi();
  }
});

const columns = [
  {
    title: '订单信息',
    dataIndex: 'orderInfo',
    key: 'orderInfo',
    width: 340,
  },
  {
    title: '货源信息',
    dataIndex: 'sourceInfo',
    key: 'sourceInfo',
    width: 340,
  },
  {
    title: '订单状态',
    dataIndex: 'orderStatus',
    key: 'orderStatus',
    width: 300,
  },
  {
    title: '利润 & 时效',
    dataIndex: 'profitTime',
    key: 'profitTime',
    width: 260,
  },
  {
    title: '订单创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180,
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    fixed: 'right',
    width: 180,
  },
];
function getDouyinOrderListFun() {
  if (!checkBindOrderApp(selectShop.value)) return;
  getDouyinOrderList({ shopId: selectShop.value }).then((res) => {
    Modal.success({
      title: '提示',
      content: res,
    });
  });
}

const fieldNames = {
  label: 'shopName',
  value: 'shopId',
};
function getListFun() {
  if (!checkBindOrderApp(selectShop.value)) return;
  getList();
}
type Key = number | string;

const selectedRowKeys = ref<Key[]>([]);
const indeterminate = ref(false);
const onSelectChange = (selectedRowKeysCb: Key[]) => {
  selectedRowKeys.value = selectedRowKeysCb;
};
function selectPrd(type: any) {
  //
  if (type) {
    onSelectChange(
      tableData.value.map((res: any) => {
        return res.tbId;
      }),
    );
    return;
  }
  onSelectChange([]);
}
const rowSelection = computed(() => {
  return {
    selectedRowKeys: unref(selectedRowKeys),
    onChange: onSelectChange,
    hideDefaultSelections: true,
   
  };
});

const showPayOrderSatatus = ref(false);
const router = useRouter();
function clickBottomButton({ type, key }: any) {
  switch (type) {
    case 'pay': {
      if (selectedRowKeys.value.length === 0) {
        return Modal.warning({
          title: '提示',
          content: '请选择订单',
        });
      }
      if (!payOrder.nowUse1688Shop || !payOrder.nowUse1688Shop.shopName) {
        Modal.confirm({
          title: '没有使用中的1688账号',
          content: '没有使用中的1688账号，前往查看 点击使用',
          onOk() {
            // window.open('/getgoods/1688shop');
            router.push('/shop-auth/shop-auth-home');
          },
        });
        return;
      }
      showPayOrderSatatus.value = true;
      const getSelectItemInfos: any = tableData.value.filter((item: any) => {
        return selectedRowKeys.value.includes(item.tbId);
      });
      payOrder.setSelectItemInfos(getSelectItemInfos, key.key);
      // payOrder.setPayType(key.key);
      break;
    }

    default: {
      break;
    }
  }
}
type changeDataType = {
  aliQuantity: number;
  tbId: number;
};
function update1688SourceFn(data: changeDataType) {

  update1688Source(data).then(() => {
   
  });
}
const openDiaLog = ref(false);
const guijiData = ref<any>({});
const pageNum=ref(1);

function seelogistics(item: any) {
  item.getguijilodin = true;
  getOrderLogisticsApi({ tbId: item.tbId })
    .then((res) => {
      guijiData.value = res;
      if (res.companyName) {
        openDiaLog.value = true;
      }
    })
    .finally(() => {
      item.getguijilodin = false;
    });
}


const showDelAliOrder = ref(false);
const tbId = ref(0);
function showDelOrderModal(record: any) {
  showDelAliOrder.value = true;
  tbId.value = record.tbId;
}

function delAliOrderApi(){
  const params = { tbId: tbId.value };

  delAliOrder(params).then((res: any) => {
    showDelAliOrder.value = false;
    if (res > 0) {
      notification.success({
        message: '采购订单状态',
        description: '清空成功',
      });
      tableData.value=[]
      getList();
    }
  });
}


</script>

<template>
  <div class="filtebox relative overflow-hidden">
    <div class="outerhuer p-4 pb-20">
      <div class="mb-4">
        <a-form layout="inline">
          <a-form-item
            class="mb-2"
            label="订单来源店铺"
            style="margin-bottom: 5px"
          >
            <a-select
              v-model:value="selectShop"
              :field-names="fieldNames"
              :options="bindShopList.filter((item) => item.pType === 2)"
              style="width: 180px"
            />
          </a-form-item>

          <a-form-item class="mb-2" label="商品名称" style="margin-bottom: 5px">
            <a-input
              v-model:value="searchForm.goodsTitle"
              allow-clear
              placeholder="请输入商品名称"
            />
          </a-form-item>

          <a-form-item
            class="mb-2"
            label="来源订单id"
            style="margin-bottom: 5px"
          >
            <a-input
              v-model:value="searchForm.dyOrderId"
              allow-clear
              placeholder="请输入"
            />
          </a-form-item>

          <a-form-item class="mb-2" label="来源订单状态">
            <a-select
              v-model:value="searchForm.dyOrderStatus"
              :field-names="{
                label: 'name',
                value: 'status',
              }"
              :options="statusOptionDouDian"
              style="width: 180px"
            />
          </a-form-item>

          <a-form-item class="mb-2" label="货源订单状态">
            <a-select
              v-model:value="searchForm.aliOrderStatus"
              :field-names="{
                label: 'name',
                value: 'aliStatus',
              }"
              :options="statusOption1688"
              style="width: 180px"
            />
          </a-form-item>

          
          <a-form-item class="mb-2" label="订单类别">
            <a-select
              v-model:value="searchForm.orderType"              
              style="width: 120px">
                <a-select-option :value="99">全部</a-select-option>
                <a-select-option :value="0">正常单</a-select-option>
                <a-select-option :value="1">特殊单</a-select-option>
                <a-select-option :value="98">采购单</a-select-option>
            </a-select>
          </a-form-item>


          <a-form-item class="mb-2">
            <a-button class="mr-2" @click="resetParams">重置</a-button>
            <a-button class="mr-2" type="primary" @click="getListFun">
              搜索
            </a-button>
            <a-button
              class="mr-2"
              type="primary"
              @click="getDouyinOrderListFun"
            >
              同步订单
            </a-button>
            <a-button class="mr-2" type="primary" @click="asyncOrderStatusApi">
              同步第三方状态
            </a-button>
          </a-form-item>
        </a-form>

        <!-- <h1 style="margin: 10px; font-size: 18px; color: red">
        如您选择第三方工具向淘宝/抖音/拼多多/快手等平台店铺分销铺货及下单采购，
        可能存在因下游平台个人信息保护要求导致1688供应商无法获得必要发货信息，可能影响您的订单发货及时性，您需关注旺旺消息或主动联系供应商配合提供必要收货信息方可正常发货
      </h1> -->
      </div>
      <div>
        
        <a-table
          :columns="columns"
          :data-source="tableData"
          :loading="loading"
          :pagination="false"
          :row-selection="rowSelection"
          :scroll="{ x: 900 }"
          row-key="tbId"
          @change="
            (da: any) => {
              console.log('change', da, size);
              if (da.pageSize !== page.pageSize) {
                handleSizeChange(da.pageSize);
                return;
              }            
              handleCurrentChange(da.current);
            }
          "
        >
          <template #bodyCell="{ column, record }">
            <OrderInfo v-if="column.key === 'orderInfo'" :order-info="record" />
            <SourceInfo
              v-if="column.key === 'sourceInfo'"
              :order-info="record"
              @update1688-source-fn="update1688SourceFn"
            />
            <OrderStatus
              v-if="column.key === 'orderStatus'"
              :order-info="record"
            />
            <ProfitTime
              v-if="column.key === 'profitTime'"
              :order-info="record"
            />
            <template v-if="column.key === 'action'">
             <a-button
                v-if="record.dyOrderStatus ===2"
                type="primary"
                @click="showDelOrderModal(record)"
              >
                清空采购订单
              </a-button>

              <a-button
                v-if="
                  record.aliOrderStatus !== null &&
                  record.aliOrderStatus !== 'waitbuyerpay'&&
                  record.aliOrderStatus !== 'waitsellersend'&&
                  record.aliOrderStatus !== 'cancel'
                "
                :loading="record.getguijilodin"
                type="primary"
                @click="seelogistics(record)"
              >
                查看物流轨迹
              </a-button>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <BottomButton
      v-model="page"
      :indeterminate="indeterminate"
      :loading="loading"
      :selected-row-keys="selectedRowKeys"
      @change-pagin="getListFun"
      @click-bottom-button="clickBottomButton"
      @get-list="getList"
      @select-prd="selectPrd"
    />
    <PayOrderBox v-model="showPayOrderSatatus" />

    <a-modal
      v-model:visible="openDiaLog"
      :footer="null"
      @cancel="openDiaLog = false"
    >
      <template #title>
        <a-space>
          <CopyItem
            :content="guijiData.logisticsBillNo"
            :title="guijiData.companyName"
          />
        </a-space>
      </template>
      <div class="py-2" style="height: 600px; overflow-y: auto">
        <a-timeline>
          <a-timeline-item
            v-for="item in guijiData.logisticsSteps"
            :key="item.acceptTime"
            color="green"
          >
            <p>{{ item.acceptTime }}</p>
            <p>{{ item.remark }}</p>
          </a-timeline-item>
        </a-timeline>
      </div>
    </a-modal>


    
      <a-modal
        v-model:visible="showDelAliOrder"
        title="是否确定要清空这个采购订单"
        @ok="delAliOrderApi"
      >
      </a-modal>
   
  </div>
</template>

<style scoped lang="scss">
.outerhuer {
  height: calc(100vh - 88px);
  overflow: hidden scroll;
}

.filtebox {
  height: calc(100vh - 88px);
  overflow: hidden;
}
</style>

<style scoped>
.ellipsis-2 {
  display: -webkit-box;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
</style>
